const app = getApp();
import { request, baseurl } from './../../utils/index.js';
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify.js';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
const watch = require("./../../utils/watch.js");
var amapFile = require('./../../utils/amap-wx.js');
var animation = wx.createAnimation({});
var i = 1;
var timer = null;
var refundtimer = null;
const recorderManager = wx.getRecorderManager();
const InnerAudioContext = wx.createInnerAudioContext();
InnerAudioContext.autoplay = false;

Page({

  /**
   * 页面的初始数据 ---- vue中的data
   */
  data: {
    recordstate : 0,  //录音标记状态  0无 1正在录音
    prolist: [],
    prolisting: [],
    prolisted: [],
    active: 0,
    abnormalFlag: false, //异常配送
    abnormalCity: '',
    radio: '1',
    abnormalList: '',
    abnormalReasonlist: [], // 异常原因列表
    abnormalReasonlists: [], // 异常原因列表
    isContacts: [], // 是否与客户联系
    currentTabs: '', // 订单异常修改原因
    isContactTabs: '', // 是否与客户联系(待配送)
    scanningFlag: true, // 扫描
    updateContents: '', // 修改内容(待配送)
    refundListFlag: false, // 退订退款标记
    refundList: '',
    pageNum: 1, // 请求页数
    sumPages01: '', // 总页数
    sumPages02: '', // 总页数
    sumPages03: '', // 总页数
  },
  // 开始录音
  startrecord: function(event){
    const token = wx.getStorageSync('token');
    if(this.recordstate===1){
      return false;
    }
    this.recordstate = 1;

    const {dataset: {index}} = event.currentTarget
    var recordclass = `prolist[${index}].recordclass`
    var recordaction = `prolist[${index}].recordaction`
    var recordPath = `prolist[${index}].recordPath`
    this.setData({
      [recordclass]:"icon-tingzhi",
      [recordaction]:"stoprecord"
    })
    recorderManager.onStart(()=>{
      
    })
    // 监听录音停止
    recorderManager.onStop((res)=>{
      this.recordstate = 0;
      let that = this;
      wx.showLoading({
        title: '上传录音中',
      })
      wx.uploadFile({
        url: '/uploadRecord', //仅为示例，非真实的接口地址
        filePath: res.tempFilePath,
        name: 'file',
        header: {
          'content-type': 'application/json', // 默认值
          'token': `${token}`
        },
        formData: {
          'order_no': event.target.dataset.item.xmbzNo
        },
        success (resfile){
          wx.hideLoading();
          resfile= JSON.parse(resfile.data);
         
          that.setData({
            [recordclass]:"icon-play",
            [recordaction]:"playrecord",
            [recordPath]:"https://audio.cdn.xiongmaodangao.com/"+resfile.key
          })
        }
        ,fail (res){
          wx.hideLoading();
          console.log(res)
        }
      })
    })

    recorderManager.onPause(function(){
    })
    // 监听录音中断
    recorderManager.onInterruptionBegin(function(){
    })
    // 监听录音中断结束
    recorderManager.onInterruptionEnd(function(){
      onsole.log("录音中断结束")
      recorderManager.resume()
    })

    recorderManager.start({
      duration:600000,
      format: "mp3",
    })
  },

  // 停止录音
  stoprecord: function(event){
    recorderManager.stop();
  },

  // 播放录音
  playrecord:function(event){
    const {dataset: {index}} = event.currentTarget
    var recordclass = `prolist[${index}].recordclass`
    var recordaction = `prolist[${index}].recordaction`
    this.setData({
      [recordclass]:"icon-zanting",
      [recordaction]:"pauserecord"
    })
    let that = this;
    InnerAudioContext.onEnded(function(){
      console.log("播放结束")
      that.setData({
        [recordclass]:"icon-play",
        [recordaction]:"playrecord"
      })
    });
    InnerAudioContext.src=event.target.dataset.recordpath
    InnerAudioContext.play()
  },
  // 暂停播放
  pauserecord:function(event){
    InnerAudioContext.pause();
    const {dataset: {index}} = event.currentTarget
    var recordclass = `prolist[${index}].recordclass`
    var recordaction = `prolist[${index}].recordaction`
    this.setData({
      [recordclass]:"icon-play",
      [recordaction]:"continuePlay"
    })
    },
    // 继续播放
    continuePlay:function(event){
      InnerAudioContext.play();
      const {dataset: {index}} = event.currentTarget
      var recordclass = `prolist[${index}].recordclass`
      var recordaction = `prolist[${index}].recordaction`
      this.setData({
      [recordclass]:"icon-zanting",
      [recordaction]:"pauserecord"
      })
    },
  // 电话拨打
  tels: function (e) {
    console.log(e.currentTarget.dataset.tel)
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.tel
    })
  },
  // 跳转详情页
  toDetail: function (e) {
    console.log(e.currentTarget.dataset.item.ordNo,e.currentTarget.dataset)
    const ordNo = e.currentTarget.dataset.item.ordNo
    wx.navigateTo({
      url: `../detail/detail?proid=${ordNo}`
    })
  },
  onChange(event) {
    if(event.detail.title === '待配送') {
      this.storage()
      this.setData({
        pageNum: 1
      })
    } else if(event.detail.title === '配送中') {
      this.storageStorage()
      this.setData({
        pageNum: 1
      })
    } else if(event.detail.title === '已完成') {
      this.storageStorageed()
      this.setData({
        pageNum: 1
      })
    }
    this.setData({
      active: event.detail.index
    })
    // wx.showToast({
    // });
  },

  /**
   * 生命周期函数--监听页面加载 --- mounted --- 请求数据
   */
  onLoad: function (options) {
    watch.setWatcher(this); // 设置监听器，建议在onLoad下调用
    this.storage()
    this.storageStorage()
    this.storageStorageed()
    this.getLocation()
    const addressFlag = wx.getStorageSync('addressFlag')
    if(addressFlag == false) {
      clearInterval(timer)
      clearInterval(refundtimer)
    } else if (addressFlag == true) {
      this.refundqueryList();
    }
  },
  /**
   * 待配送
   */
  storage(token) {
    //console.log(token)
    try {
      const token = wx.getStorageSync('token')
      const distributorId = wx.getStorageSync('distributorId')
      request({
        url: '/queryOrder',
        method: 'GET',
        data: {
          token: token,
          ordState: 6,
          distributorId: distributorId,
          pageNum: 1,
          pageSize: 10,
        },
        header: {
          'content-type': 'application/json', // 默认值
          'token': `${token}`
        }
      }).then(res => {
        if(res.data.list !== undefined) {
          if (res.data.list == '') {
            this.setData({
              prolist: '',
              pageNum: 1,
              sumPages01: 0
            })
          } else {
            const result = res.data.list
            const sumPages01 = res.data.pages
            // let status = []
            console.log('66666',sumPages01)
            result.forEach((item,index) => {
              console.log(typeof result[index],'result[index]')
              result[index].status = []
              if(result[index].orderDetailList) {
                // 标记对应订单的录音状态
                if( result[index].recordPath){
                  result[index].recordclass='icon-play';
                  result[index].recordaction='playrecord';
                }else{
                  result[index].recordclass='icon-record';
                  result[index].recordaction='startrecord';
                }
                result[index].orderDetailList.forEach((isScanitem,isScanindex) => {
                  result[index].status.push(result[index].orderDetailList[isScanindex].isScan)
                })
              }
              if(result[index].status.indexOf(0) > -1) {
                result[index].scanningFlag = true
              } else {
                result[index].scanningFlag = false
              }
            })
            // console.log(result,'result')
            this.setData({
              prolist: result,
              pageNum: 1,
              sumPages01
            })  
          }
        }
        if(res.data.msg !== undefined) {
          Notify({
            message: `${res.data.msg}`,
            type: 'danger'
          })
        }
      })
    } catch (e) {
      console.error(e,'error')
    }
  },
  // /**
  //  * 配送中
  //  */
  storageStorage(token) {
    try {
      const token = wx.getStorageSync('token')
      const distributorId = wx.getStorageSync('distributorId')
      if(token !== ''){
        request({
          url: '/queryOrder',
          method: 'GET',
          data: {
            token: token,
            ordState: 7,
            distributorId,
            pageNum: 1,
            pageSize: 10
          },
          header: {
            'content-type': 'application/json',
            'token': `${token}`
          }
        }).then(res => {
          if(res.data.list !== undefined) {
            if (res.data.list == '') {
              this.setData({
                prolisting: '',
                pageNum: 1,
                sumPages02: 0
              })
            } else {
              let result = res.data.list;
              const sumPages02 = res.data.pages;
              result.forEach((item,index) => {
                // 标记对应订单的录音状态
                if( result[index].recordPath){
                  result[index].recordclass='icon-play';
                  result[index].recordaction='playrecord';
                }else{
                  result[index].recordclass='icon-record';
                  result[index].recordaction='startrecord';
                }
                result[index].status = []
                if(result[index].orderDetailList) {
                  result[index].orderDetailList.forEach((isScanitem,isScanindex) => {
                    result[index].status.push(result[index].orderDetailList[isScanindex].isScan)
                  })
                }
                if(result[index].status.indexOf(0) > -1) {
                  result[index].scanningFlag = true
                } else {
                  result[index].scanningFlag = false
                }
              })
              this.setData({
                prolisting: result,
                pageNum: 1,
                sumPages02
              })
            }
          }
          if(res.data.msg !== undefined) {
            Notify({
              message: `${res.data.msg}`,
              type: 'danger'
            })
          }
        })
      }
    } catch (e) {
      //console.error(e)
    }
  },

  /**
   * 立即配送中
   */
  storageing(e) {
    try {
      const token = wx.getStorageSync('token')
      const ordNo = e.currentTarget.dataset.item.ordNo
      const distributorId = wx.getStorageSync('distributorId')
      request({
        url: '/deliveryOrder',
        method: 'GET',
        data: {
          token,
          ordNo,
          // distributorId
        },
        header: {
          'content-type': 'application/json', // 默认值
          'token': `${ token }`
        }
      }).then(res => {
        if(res.data.code == 200) {
          wx.showToast({
            title: '配送成功',
            icon: 'success',
            duration: 2000
          })
          this.storage();
          this.storageStorage();
        } else {
          Notify({
            message: `${res.data.msg}`,
            type: 'danger'
          })
        }
      })
    } catch (e) {
      console.error(e)
    }
  },
  // /**
  //  * 已完成
  //  */
  storageStorageed(token) {
    //console.log(token)
    try {
      const token = wx.getStorageSync('token')
      const distributorId = wx.getStorageSync('distributorId')
      // console.log(typeof token)
      if(token !== '') {
        request({
        url: '/queryOrder',
        method: 'GET',
        data: {
          token: token,
          ordState: 8,
          distributorId,
          pageNum: 1,
          pageSize: 10
        },
        header: {
          'content-type': 'application/json',
          'token': `${token}`
        }
      }).then(res => {
        if(res.data.list !== undefined) {
          let result = res.data.list;
          const sumPages03 = res.data.pages;
          if (result == '') {
            this.setData({
              prolisted: '',
              pageNum: 1,
              sumPages03: 0
            })
          } else {
            this.setData({
              prolisted: result,
              pageNum: 1,
              sumPages03
            })
          }
        }
        if(res.data.msg !== undefined) {
          Notify({
            message: `${res.data.msg}`,
            type: 'danger'
          })
        }
      })
      }
    } catch (e) {
      //console.error(e)
    }
  },
  /**
   * 签收订单
   */
  getMessstorageing(e) {
    this.getLocation()
    try {
      const token = wx.getStorageSync('token')
      const longitude = wx.getStorageSync('userLongitude')
      const latitude = wx.getStorageSync('userLatitude')
      const ordNo = e.currentTarget.dataset.item.ordNo
      Dialog.confirm({
        title: '签收订单',
        message: ' ',
        width: '93%',
        messageAlign: 'center',
      }).then(() => {
        request({
          url: '/signOrder',
          method: 'GET',
          data: {
            token,ordNo,longitude,latitude
          },
          header: {
            'content-type': 'application/json',
            'token': `${token}`
          }
        }).then(res => {
          // console.log(res.data.code)
          if(res.data.code == 200) {
            Notify({
              message: '签收成功!',
              type: 'success'
            })
            this.storageStorage()
            this.storageStorageed()
          } else if (res.data.code == -1) {
            Notify({
              message: `${res.data.msg}`,
              type: 'danger'
            })
          } else {
            Notify({
              message: `${res.data.msg}`,
              type: 'danger'
            })
          }
        })
        // on close
      }).catch(() => {
        // on cancel
      });
    } catch (e) {
      console.error(e)
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(this.recordstate==1){
      recorderManager.resume()
    }
    // this.recordstate = 0;
    const _this = this
    const token = wx.getStorageSync('token')
    if (token == '') {
      wx.setStorageSync('addressFlag', false)
      this.setData({
        prolist: '',
        prolisting: '',
        prolisted: '',
      })
      // console.log('addressFlag',addressFlag)
      const addressFlag = wx.getStorageSync('addressFlag')
      if(addressFlag == false) {
        // console.log('false01')
        timer = null;
        clearInterval(timer)
        console.log('refundtimer')
        clearInterval(refundtimer)
      }
    } else {
      // this.storage()
      this.storageStorage()
      this.storageStorageed()
      this.getLocation()
      // console.log('false02')
      const addressFlag = wx.getStorageSync('addressFlag')
      if(addressFlag == true) {
        this.isrefundTimer()
      }
      // if(addressFlag == true) {
      //   console.log('this.timer',timer)
      //   if (timer !== null) {
      //     console.log('this.timer',timer)
      //     clearInterval(timer)
      //   }
      //   timer = setInterval(function () {
      //     console.log('this.timer',timer)
      //     _this.storage()
      //     _this.storageStorage()
      //     _this.storageStorageed()
      //     _this.getLocation()
      //   }, 5000)
      // } else {
      //   console.log('false01')
      //   timer = null;
      //   clearInterval(timer)
      // }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    if(this.recordstate==1){
      recorderManager.pause()
    }
    console.log('onHide')
    const addressFlag = wx.getStorageSync('addressFlag')
    if(addressFlag == false) {
      // console.log('808098')
      timer = null;
      clearInterval(timer)
      clearInterval(refundtimer)
    }
    clearInterval(refundtimer)
    // clearInterval(timer)
    // clearInterval(timer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // clearInterval(timer)
    // console.log('onUnload')
  },
  onChangeAbnormal(e) {
    this.setData({
      radio: e.detail,
    });
  },
  // 异常配送
  abnormalDeliverly(e) {
    console.log('已成配送')
    console.log(e.currentTarget.dataset)
    // this.setData({
    //   abnormalFlag: true,
    //   abnormalList: e.currentTarget.dataset.item.ordNo,
    //   abnormalCity: e.currentTarget.dataset.item.cityName
    // })
    const ordNo = e.currentTarget.dataset.item.ordNo
    const cityName = e.currentTarget.dataset.item.cityName
    wx.navigateTo({
      url: `../abnoquery/abnoquery?proid=${ordNo}&&city=${cityName}`
    })
    this.getabnormalReasonlist()
    this.getCustomerContact()
  },
  
  // 异常配送获取修改原因列表
  getabnormalReasonlist() {
    console.log('1324234324')
    try {
      const token = wx.getStorageSync('token')
      request({
        url: '/getDictInfo',
        method: 'GET',
        data: {
          token: token,
          dictCode: 'customer_issues'
        },
        header: {
          'content-type': 'application/json', // 默认值
          'token': `${token}`
        }
      }).then(res => {
        // console.log(res.data.result)
        if(res.data.code == 200) {
          this.setData({
            abnormalReasonlist: res.data.result.dictList,
            // abnormalReasonlists: res.data.result.dictList
          })
        } else {
          Notify({
            message: `${res.data.msg}`,
            type: 'danger'
          })
        }
      })
    } catch (e) {
      //console.error(e)
    }
    try {
      const token = wx.getStorageSync('token')
      request({
        url: '/getDictInfo',
        method: 'GET',
        data: {
          token: token,
          dictCode: 'domestic_question'
        },
        header: {
          'content-type': 'application/json', // 默认值
          'token': `${token}`
        }
      }).then(res => {
        if(res.data.code == 200) {
          console.log(res.data.result,'3412343')
          this.setData({
            // abnormalReasonlist: res.data.result.dictList,
            abnormalReasonlists: res.data.result.dictList
          })
        } else {
          Notify({
            message: `${res.data.msg}`,
            type: 'danger'
          })
        }
      })
    } catch (e) {
      //console.error(e)
    }
  },
  // 取消操作
  cancelAbnormal() {
    const _this = this
    this.setData({
      abnormalFlag: false,
    })
    setTimeout(function() {
      _this.setData({
        abnormalList: '',
        updateContents: '',
        abnormalCity: '',
        currentTabs: '',
        isContactTabs: ''
      })
    },2000)
  },
  formSubmit: function (e) {
    // console.log(e.detail.value['1'])
    const orderId = e.currentTarget.dataset.id
    const delivery = wx.getStorageSync('resetname')
    const deliveryUnusualReason = e.currentTarget.dataset.deliveryunusualreason
    const customerContact = e.currentTarget.dataset.customercontact
    const updateContent = e.currentTarget.dataset.updatecontent
    if(deliveryUnusualReason == '' || customerContact == '' || updateContent == '') {
      Dialog.alert({
        title: '提示',
        message: '您还有信息未填，请完善信息！',
      }).then(() => {
        // on close
      });
    } else {
      try {
        const token = wx.getStorageSync('token')
        if (token !== '') {
          request({
            url: '/addOrderDeliveryAbnormal',
            method: 'POST',
            data: {
              delivery,
              orderId,
              deliveryUnusualReason,
              customerContact,
              updateContent
            },
            header: {
              'content-type': 'application/json', // 默认值
              'token': `${token}`
            }
          }).then(res => {
            if (res.data.code == 200) {
              wx.showToast({
                title: '成功',
                icon: 'success',
                duration: 2000
              })
              this.setData({
                abnormalFlag: false,
                abnormalList: '',
                updateContents: '',
                abnormalCity: '',
                currentTabs: '',
                isContactTabs: '',
              })
            } else if (res.data.code == 40003) {
              // wx.showToast({
              //   title: '您已提交异常配送信息,请耐心等待!',
              //   icon: 'warning',
              //   duration: 2000
              // })
              this.setData({
                abnormalFlag: false
              })
              Notify({
                message: `${res.data.msg}`,
                type: 'danger'
              })
            } else {
              Notify({
                message: `${res.data.msg}`,
                type: 'danger'
              })
            }
            console.log(e,'25000')

          })
        }
      } catch (e) {
        //console.error(e)
      }
    }
  },
  formSubmiting: function(e) {
    console.log('formSubmiting',e)
    const _this = this
    const orderId = e.currentTarget.dataset.id
    const delivery = wx.getStorageSync('name')
    const deliveryUnusualReason = e.currentTarget.dataset.deliveryunusualreason
    const customerContact = e.currentTarget.dataset.customercontact
    const updateContent = e.currentTarget.dataset.updatecontent
    if(deliveryUnusualReason == '' || customerContact == '' || updateContent == '') {
      Dialog.alert({
        title: '提示',
        message: '您还有信息未填，请完善信息！',
      }).then(() => {
        // on close
      });
    } else {
      try {
        const token = wx.getStorageSync('token')
        if (token !== '') {
          const token = wx.getStorageSync('token')
          request({
            url: '/addOrderDeliveryAbnormal',
            method: 'POST',
            data: {
              orderId,
              delivery,
              deliveryUnusualReason,
              customerContact,
              updateContent
            },
            header: {
              'Content-Type': 'application/json',
              'token': `${token}`
            }
          }).then(res => {
            if (res.data.code == 200) {
              wx.showToast({
                title: '成功',
                icon: 'success',
                duration: 2000
              })
              this.setData({
                abnormalList: '',
              })
            } else if(res.data.code == 40003) {
              Notify({
                message: '您已提交异常配送信息,请耐心等待!',
                type: 'danger'
              })
              _this.storage()
              _this.storageStorage()
              _this.storageStorageed()
            } else {
              Notify({
                message: `${res.data.msg}`,
                type: 'danger'
              })
            }
            console.log('25000')
  
          })
        }
      } catch (e) {
        //console.error(e)valueAbnormal
      }
    }
  },
  // 异常配送
  abnormalDeliverlying(e) {
    // console.log(e.currentTarget.dataset.item.cityName)
    const ordNo = e.currentTarget.dataset.item.ordNo
    const cityName = e.currentTarget.dataset.item.cityName
    const xmbzNo = e.currentTarget.dataset.item.xmbzNo
    wx.navigateTo({
      url: `../abnoquery/abnoquery?proid=${ordNo}&&city=${cityName}&&xmbzNo=${xmbzNo}`
    })
    this.getabnormalReasonlist()
    this.getCustomerContact()
  },
  // 取消操作
  cancelAbnormaling() {
    const _this = this
    setTimeout(function() {
      _this.setData({
        abnormalList: '',
      })
    },2000)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   * 重新请求了第一页的数据
   */
  onPullDownRefresh: function () {
    console.log('刷新当前页面')
    const _this = this;
    wx.setBackgroundTextStyle({
      text: '加载中' // 下拉背景字体、loading 图的样式为dark
    })
    // 显示标题栏进度条效果
    wx.showNavigationBarLoading()
    const token = wx.getStorageSync('token')
    if (token == '') {
      this.setData({
        prolist: '',
        prolisting: '',
        prolisted: '',
      })
    } else {
      this.storage()
      this.storageStorage()
      this.storageStorageed()
      const addressFlag = wx.getStorageSync('addressFlag')
      if(addressFlag == true) {
        _this.refundqueryList();
      }
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    }
  },

  /**
   * 用户点击右上角分享
   * 可以通过微信提供的api修改分享的内容
   */
  onShareAppMessage: function () {
    // console.log('你准备好分享了吗')
  },

  /**
   * 页面滚动触发事件的处理函数
   * 默认的参数就是滚动条距离顶部的距离 - options
   * 滚动到某一个位置，出现返回顶部按钮
   */
  onPageScroll(options) {
  },

  /**
   * 当前是 tab 页时，点击 tab 时触发
   * 就是全局配置的底部选项卡
   */
  onTabItemTap() {
    // console.log('首页')
  },
  /**
   * 异常配送点击修改原因颜色改变，并获取对应的值(待配送)
   */
  getAbnormalReasons(e) {
    // console.log(e.currentTarget.dataset)
    // this.setData({
    //   currentTabs: e.currentTarget.dataset.dictvalue,
    // })
  },
  /**
   * 异常配送点击修改原因颜色改变，并获取对应的值
   */
  getAbnormalReason(e) {
    // console.log(e.currentTarget.dataset)
    this.setData({
    })
  },
  /**
   * 是否与客户联系颜色改变，并获取对应的值
   */
  getisContact(e) {
    this.setData({
    })
  },
  /**
   * 异常订单修改内容，并获取对应的值(配送中)
   */
  getUpdateContentCopy(e){
    // console.log(e.detail.length,'e.currentTarget.dataset')
    if(e.detail.length > 100) {
      Notify({
        message: '您输入的内容已超出，请重新编辑!',
        type: 'danger'
      })
    } else {
      this.setData({
        updateContent: e.detail.replace(/\s+/g, '')
      })
    }
  },
  /**
   * 异常订单修改内容，并获取对应的值(待配送)
   */
  getUpdateContent(e){
    // console.log(e.detail.length,'e.currentTarget.dataset')
    if(e.detail.length > 100) {
      Notify({
        message: '您输入的内容已超出，请重新编辑!',
        type: 'danger'
      })
    } else {
      this.setData({
        updateContents: e.detail
      })
    }
  },
  // 异常配送是否与客户联系列表
  getCustomerContact() {
    try {
      const token = wx.getStorageSync('token')
      request({
        url: '/getCustomerContact',
        method: 'GET',
        data: {
          token: token
        },
        header: {
          'content-type': 'application/json', // 默认
          'token': `${token}`
        }
      }).then(res => {
        if(res.data.code == 200) {
          console.log(res.data.result)
          this.setData({
            isContacts: res.data.result.dictList
          })
        } else {
          Notify({
            message: `${res.data.msg}`,
            type: 'danger'
          })
        }
      })
    } catch (e) {
      //console.error(e)
    }
  },
  /**
   * 扫码入库
   */
  scanningWarehousing(e) {
    console.log('e扫描',e.currentTarget.dataset.id,)
    const thisOrderId = e.currentTarget.dataset.id;
    const thisDetailId = e.currentTarget.dataset.item.orderDetailList;
    const thisDetailIdArray = []
    thisDetailId.forEach(item => {
      thisDetailIdArray.push(item.id)
    })
    console.log('thisDetailIdArray',thisDetailIdArray,thisDetailIdArray.length)
    this.getScancode(thisOrderId,thisDetailIdArray)
  },
  /**
   * 扫码
   */
  getScancode: function(thisOrderId,thisDetailIdArray) {
    var _this = this;
    // 允许从相机和相册扫码
    wx.scanCode({
      success: (res) => {
        var result = res.result;
        console.log(result)
        try {
          var detailFlag = false;
          const token = wx.getStorageSync('token');
          const distributorId = wx.getStorageSync('distributorId');
          let orderId = -1;
          let orderDetailId = null;
          try {
            //兼容条码模式
            var json = JSON.parse(result);
            if(json.orderId === undefined) {
              orderDetailId = json;
            } else{
              orderId = json.orderId;
              orderDetailId = json.orderDetailId;
            }
          } catch(e){
            orderDetailId = result;
          }
          if(thisDetailIdArray.indexOf(orderDetailId) > -1) { 
            detailFlag = true;
          } else {
            detailFlag = false;
          }
          if((orderId == -1 || orderId == thisOrderId) && detailFlag) {
            if(token !== ''){
              request({
                url: '/addDeliveryScanLog',
                method: 'POST',
                data: {
                  token,
                  orderId,
                  orderDetailId,
                  distributorId
                },
                header: {
                  'Content-Type': 'application/x-www-form-urlencoded',
                  'token': `${token}`
                }
              }).then(res => {
                if(res.data.code == 200) {
                  this.storage()          
                  this.storageStorage()
                  this.storageStorageed()
                  wx.showToast({
                    title: '扫描成功',
                    icon: 'success',
                    duration: 2000
                  })
                  // console.log('res扫码入库',res.data)
                } else {
                  Notify({
                    message: `${res.data.msg}`,
                    type: 'danger'
                  })
                }
              })
            }
          } else {
            console.log('订单不符合')
            Notify({
              message: '拿错啦！这不是此订单的蛋糕',
              type: 'danger'
            })
          }
        } catch (e) {
          //console.error(e)
        }
      },
      fail(e) {
        console.log(e)
      }
    })
  },
  /**
   * 自定义的数据以及函数就可以写
   * 页面离不开事件 --- 自定义的函数
   */
  testfn() {
    // console.log('自定义函数')
  },
  getAddress() {
    var myAmapFun = new amapFile.AMapWX({key:'d5e940ac71e33d85ec6ebad1c485e99e'});
    myAmapFun.getRegeo({
      success:(res)=>{
        // console.log('都给你钱定位',res,res[0].longitude,res[0].latitude)
        wx.setStorageSync('userLongitude', res[0].longitude)
        wx.setStorageSync('userLatitude', res[0].latitude)
        // wx.setStorageSync('addressLocation', res[0].name)
        try {
          const token = wx.getStorageSync('token')
          const account = wx.getStorageSync('name')
          const userId = wx.getStorageSync('distributorId')
          const longitude = res[0].longitude
          const latitude = res[0].latitude
          if (token !== '') {
            request({
              url: '/addUserPosition',
              method: 'POST',
              data: {
                userId,
                account,
                longitude,
                latitude,
              },
              header: {
                'content-type': 'application/json', // 默认值
                'token': `${token}`
              }
            }).then(res => {
              if (res.data.code == 200) {
              }
            })
          }
        } catch (e) {
          //console.error(e)
        }
      }
    })
  },
  // getUserLocation() {
  //   wx.getSetting({
  //     success(res) {
  //       console.log(res)
  //       if (res.authSetting['scope.userLocationBackground']) {
  //         wx.startLocationUpdateBackground({
  //           success: (res) => {
  //             console.log('startLocationUpdate-res', res)
  //           },
  //           fail: (err) => {
  //             console.log('startLocationUpdate-err', err)
  //           }
  //         })
  //       } else {
  //         if (res.authSetting['scope.userLocation']==false) {
  //           console.log('打开设置页面去授权')
  //         } else {
  //           wx.startLocationUpdateBackground({
  //             success: (res) => {
  //               console.log('startLocationUpdate-res', res)
  //             },
  //             fail: (err) => {
  //               console.log('startLocationUpdate-err', err)
  //             }
  //           })
  //         }
  //       }
  //     }
  //   })
  // },
  // getAddress() {
  //   try {
  //     const token = wx.getStorageSync('token')
  //     const account = wx.getStorageSync('name')
  //     const userId = wx.getStorageSync('distributorId')
  //     const longitude = wx.getStorageSync('userLongitude')
  //     const latitude = wx.getStorageSync('userLatitude')
  //     console.log('wx.',wx.getStorageSync('longitude'))
  //     if (token !== '') {
  //       request({
  //         url: '/addUserPosition',
  //         method: 'POST',
  //         data: {
  //           userId,
  //           account,
  //           longitude,
  //           latitude,
  //         },
  //         header: {
  //           'content-type': 'application/json', // 默认值
  //           'token': `${token}`
  //         }
  //       }).then(res => {
  //         if (res.data.code == 200) {
  //           // console.log(res.data,'传成功了')
  //           // wx.showToast({
  //           //   title: '成功',
  //           //   icon: 'success',
  //           //   duration: 2000
  //           // })
  //         }
  //       })
  //     }
  //   } catch (e) {
  //     //console.error(e)
  //   }
  // },
  /**
   * 地图跳转高高德
   */
  getLocation() {
    const _this = this;
    this.getAddress()
    const addressFlag = wx.getStorageSync('addressFlag')
    // console.log('addressFlag',addressFlag,wx.getStorageSync('addressFlag'))
    // this.getUserLocation();
    // const _locationChangeFn = res=> {
    //   console.log('location change',res, res.latitude, res.longitude)
    //   wx.setStorageSync('userLongitude', res.longitude)
    //   wx.setStorageSync('userLatitude', res.latitude)
    //   console.log('wx.getStorageSync(',wx.getStorageSync('userLongitude'))
    //   // latitude = res.latitude;
    //   // longitude = res.longitude;
    // }
    // wx.onLocationChange(_locationChangeFn);
    // this.getAddress()
  },
  openLocation(e) {
    console.log('ditu ',e.currentTarget.dataset.item,e.currentTarget.dataset.item.addressLat)
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        wx.openLocation({//​使用微信内置地图查看位置。
          latitude: Number(e.currentTarget.dataset.item.addressLat),//要去的纬度-地址
          longitude: Number(e.currentTarget.dataset.item.addressLng),//要去的经度-地址
          name: e.currentTarget.dataset.item.address2,
          address: e.currentTarget.dataset.item.address2
        })
      }
    })
    // wx.openLocation()
  },
  ////
  isTimer() {
    const addressFlag = wx.getStorageSync('addressFlag');
    const _this = this;
    if(addressFlag == true) {
      if (timer !== null ) {
        clearInterval(timer);
      }
      timer = setInterval(function () {
        _this.storage()
        _this.storageStorage()
        _this.storageStorageed()
        _this.getLocation()
      }, 60*60*1000)
    } else {
      // console.log('false01')
      timer = null;
      clearInterval(timer);
      clearInterval(refundtimer)
    }
  },
  /**
   * 监听定时器 
   */ 
  watch: {
    'prolist': function(){
      const addressFlag = wx.getStorageSync('addressFlag')
      if(addressFlag == true) {
        this.isTimer();
      }
    }
  },
  // 列表置顶
  Topping(e) {
    // console.log('e',e.currentTarget.dataset.item,e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index;
    if(index > 0) {
      let busArr = []; //获取数组
      if(e.currentTarget.dataset.status == 6) {
        busArr = this.data.prolist;//获取列表中的所有数组
      } else if(e.currentTarget.dataset.status == 7) {
        busArr = this.data.prolisting;//获取列表中的所有数组
      } else if(e.currentTarget.dataset.status == 8) {
        busArr = this.data.prolisted;//获取列表中的所有数组
      }
      // busArr.splice(index,1,busArr[0]);
      // console.log('index',index)
      busArr.splice(index,1);
      busArr.splice(0,0,e.currentTarget.dataset.item);
      if(e.currentTarget.dataset.status == 6) {
        this.setData({prolist:busArr});
      } else if(e.currentTarget.dataset.status == 7) {
        this.setData({prolisting:busArr});
      } else if(e.currentTarget.dataset.status == 8) {
        this.setData({prolisted:busArr});
      }
    }
  },
  /**
   * 列表向上一级
   */
  ColumnUp(e) {
    // console.log('e',e.currentTarget.dataset.item,e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index;
    if(index > 0) {
      let busArr = []; //获取数组
      if(e.currentTarget.dataset.status == 6) {
        busArr = this.data.prolist;//获取列表中的所有数组
      } else if(e.currentTarget.dataset.status == 7) {
        busArr = this.data.prolisting;//获取列表中的所有数组
      } else if(e.currentTarget.dataset.status == 8) {
        busArr = this.data.prolisted;//获取列表中的所有数组
      }
      busArr.splice(index,1,busArr[index - 1]);
      busArr.splice(index - 1,1,e.currentTarget.dataset.item);
      if(e.currentTarget.dataset.status == 6) {
        this.setData({prolist:busArr});
      } else if(e.currentTarget.dataset.status == 7) {
        this.setData({prolisting:busArr});
      } else if(e.currentTarget.dataset.status == 8) {
        this.setData({prolisted:busArr});
      }
    }
  },
  /**
   * 退订退款定时器
   */
  isrefundTimer() {
    const addressFlag = wx.getStorageSync('addressFlag');
    const _this = this;
    if(addressFlag == true) {
      _this.refundqueryList();
      // console.log('refundtimer','true')
      if (refundtimer !== null ) {
        clearInterval(refundtimer);
      }
      refundtimer = setInterval(function () {
        _this.refundqueryList();
      }, 30*1000)
    } else {
      console.log('refundtimer','false')
      clearInterval(refundtimer)
    }
  },
  /**
   * 退订退款订单请求
   */
  refundqueryList() {
    try {
      const token = wx.getStorageSync('token');
      const delivery = wx.getStorageSync('resetname')
      const deliveryId = wx.getStorageSync('distributorId');
      request({
        url: '/getOrderRefundLogList',
        methods: 'GET',
        data: {
          delivery,
          deliveryId
        },
        header: {
          'content-type': 'application/json',
          // 'content-type': 'application/x-www-form-urlencoded',
          'token': `${token}`
        }
      }).then(res => {
        // console.log('res退订退款',res.data.result)
        if(res.data.code == 200) {
          let result = res.data.result.orderRefundLogVoListList;
          result.forEach((item,index) => {
            if(result[index].deliveryStartTime !== undefined) {
              result[index].StartTime = result[index].deliveryStartTime.substring(5,16);
              result[index].StartTime = result[index].StartTime.replace('T',' ');
              result[index].EndTime = result[index].deliveryEndTime.substring(11,16);
              result[index].EndTime = result[index].EndTime.replace('T',' ')
            }
            let cakestr = result[index].goodsNames;
            let cakeArray = cakestr.split(',');
            let iscanstr = result[index].isScans;
            let iscanArray = iscanstr.split(',');
            result[index].orderDetailList = [];
            if(iscanArray.length > 0) {
              iscanArray.forEach((iscanitem,iscanindex) => {
                result[index].orderDetailList[iscanindex] = {'isScan': '','goodsName': ''}
                result[index].orderDetailList[iscanindex].isScan = iscanitem;
              })
            }
            if(cakeArray.length > 0) {
              cakeArray.forEach((cakeitem,cakeindex) => {
                result[index].orderDetailList[cakeindex].goodsName = cakeitem;
              })
            }
            // console.log(cakeArray,'cakeArray',result,'iscanArray')
          })
          this.setData({
            refundList: result,
            refundListFlag: true
          })
        } else {
          Notify({
            message: `${res.data.msg}`,
            type: 'danger'
          })
        }
      })
    } catch (e) {
      console.log('e')
    }
  },
  // 退订退款确认
  refundSubmiting(e) {
    const id = e.currentTarget.dataset.id;
    const delivery = wx.getStorageSync('resetname')
    try {
      const token = wx.getStorageSync('token')
      request({
        url: '/readOrderRefundLog',
        method: 'GET',
        data: {
          id,
          delivery
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded', // 默认
          'token': `${token}`
        }
      }).then(res => {
        if(res.data.code == 200) {
          wx.showToast({
            title: '操作成功',
            icon: 'success',
            duration: 2000
          })
          this.refundqueryList();
          this.storage();
          this.storageStorage();
          this.storageStorageed();
        } else {
          Notify({
            message: `${res.data.msg}`,
            type: 'danger'
          })
        }
      })
    } catch (e) {
      //console.error(e)
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   * 上拉加载
   * 
   */
  onReachBottom: function() {
    console.log(this.data,'this.data')
    let ordState = '';
    if(this.data.active == 0) {// 待配送
      console.log('this.data',)
      ordState = 6;
      this.Tobedeliver(ordState);
    } else if (this.data.active == 1) {// 配送中
      ordState = 7;
      this.Tobedeliver(ordState);
    } else if (this.data.active == 2) {// 已签收
      ordState = 8;
      this.Tobedeliver(ordState);
    }
  },
  /**
   * 配送上拉拉加载
   */
  Tobedeliver(ordState) {
    let num = this.data.pageNum
    let sumPages = '';
    num += 1;
    if(this.data.active == 0) {// 待配送
      sumPages = this.data.sumPages01;
      console.log('pageNum',sumPages)
    } else if (this.data.active == 1) {// 配送中
      sumPages = this.data.sumPages02;
      console.log('pageNum',sumPages)
    } else if (this.data.active == 2) {// 已签收
      sumPages = this.data.sumPages03;
      console.log('pageNum',sumPages)
    }
    if(num > sumPages) {
      Notify({
        message: '没有更多数据了！',
        type: 'warning'
      })
    } else {
      try {
        const token = wx.getStorageSync('token')
        const distributorId = wx.getStorageSync('distributorId')
        if(token !== '') {
          request({
            url: '/queryOrder',
            method: 'GET',
            data: {
              token,
              ordState,
              distributorId,
              pageNum: num,
              pageSize: 10
            },
            header: {
              'content-type': 'application/json', // 默认值
              'token': `${token}`
            }
          }).then(res => {
            let arr = [] // 获取数据
            if(this.data.active == 0) {// 待配送
              arr = this.data.prolist
            } else if (this.data.active == 1) {// 配送中
              arr = this.data.prolisting
            } else if (this.data.active == 2) {// 已签收
              arr = this.data.prolisted
            }
            let list = [...arr, ...res.data.list] // 处理数据
            if (res.data.list == '') {
              if(this.data.active == 0) {// 待配送
                this.setData({
                  prolist: '',
                  pageNum: num
                })
              } else if (this.data.active == 1) {// 配送中
                this.setData({
                  prolisting: '',
                  pageNum: num
                })
              } else if (this.data.active == 2) {// 已签收
                this.setData({
                  prolisted: '',
                  pageNum: num
                })
              }
            } else {
              const result = list;
              // let status = []
              result.forEach((item,index) => {
                if( result[index].recordPath){
                  result[index].recordclass='icon-play';
                  result[index].recordaction='playrecord';
                }else{
                  result[index].recordclass='icon-record';
                  result[index].recordaction='startrecord';
                }
                result[index].status = []
                if(result[index].orderDetailList) {
                  result[index].orderDetailList.forEach((isScanitem,isScanindex) => {
                    result[index].status.push(result[index].orderDetailList[isScanindex].isScan)
                  })
                }
                if(result[index].status.indexOf(0) > -1) {
                  result[index].scanningFlag = true
                } else {
                  result[index].scanningFlag = false
                }
              })
              if(this.data.active == 0) {// 待配送
                console.log('待配送')
                this.setData({
                  prolist: list,
                  pageNum: num
                })
              } else if (this.data.active == 1) {// 配送中
                console.log('配送中')
                this.setData({
                  prolisting: list,
                  pageNum: num
                })
              } else if (this.data.active == 2) {// 已签收
                console.log('已签收')
                this.setData({
                  prolisted: list,
                  pageNum: num
                })
              }
            }
            if(res.data.msg !== undefined) {
              Notify({
                message: `${res.data.msg}`,
                type: 'danger'
              })
            }
          })
        }
        
      } catch (e) {
        console.error(e,'error')
      }
    }
  },
  /**
   * 配送中下拉加载
   */
  Deliverying() {

  },
  /**
   * 已签收下拉加载
   */
  Signed() {

  },
  clipboardData(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success (res) {
        
      }
    })
  }
  
})